package cn.xfdtool.slowsql.listener.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.xfdtool.slowsql.config.SlowSQLConfig;
import cn.xfdtool.slowsql.dto.SlowSQLDTO;
import cn.xfdtool.slowsql.listener.SlowSQLMatchListener;
import java.util.Collection;

/**
 * 慢SQL或者异常SQL匹配器
 *
 * @author xfd
 * 2022/5/14
 */
public class SlowOrErrorSQLMatchListener implements SlowSQLMatchListener {

    private SlowSQLConfig slowSQLConfig;

    public SlowOrErrorSQLMatchListener(SlowSQLConfig slowSQLConfig) {
        this.slowSQLConfig = slowSQLConfig;
    }
    @Override
    public boolean isMatch(SlowSQLDTO slowSQLDTO) {
        // 是否是debug模式
        if (slowSQLConfig.isDebug()) {
            return true;
        }
        // 异常SQL
        if (ObjectUtil.isNotEmpty(slowSQLDTO.getThrowable())) {
            return true;
        }
        // 慢SQL判断
        long total = slowSQLDTO.getEnd() - slowSQLDTO.getStart();
        if (total >= ((slowSQLConfig.getSlowSQLTime() <= 0 ? SlowSQLConfig.DEFAULT_SLOWSQL_TIME : slowSQLConfig.getSlowSQLTime()) * 1000)) {
            return true;
        }
        // 大SQL判断
        if (ObjectUtil.isNotEmpty(slowSQLDTO.getResult())) {
            if (slowSQLDTO.getResult() instanceof Collection) {
                Collection coll = (Collection) slowSQLDTO.getResult();
                return coll.size() >= (slowSQLConfig.getMaxRowCount() <= 0 ? SlowSQLConfig.DEFAULT_SLOWSQL_MAXROWCOUNT : slowSQLConfig.getMaxRowCount());
            }
        }
        return false;
    }
}
